/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-09-15 09:42:16
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-09-17 15:30:39
 * @FilePath: /Learn/Thread/mythread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<string>
#include<cstdlib>
#include<unistd.h>
#include<pthread.h>
using namespace std;
class Request
{
public:
    Request(int start,int end,const string&threadname)
        :_start(start)
        ,_end(end)
        ,_threadname(threadname)
        {}
public:
    int _start;
    int _end;
    string _threadname;
};

class Response
{
public:
    Response(int result,int exitcode)
        :_result(result)
        ,_exitcode(exitcode)
        {}
public:
    int _result;//计算结果
    int _exitcode;//计算结果是否可靠
};

//线程的参数和返回值，不仅仅可以用来传递一般参数，还可以用来传递对象
void*sumCount(void*args)
{
    Request *rq=static_cast<Request*>(args);//类型转换
    Response *rsq=new Response(0,0);
    for(int i=rq->_start;i<rq->_end;i++)
    {
        rsq->_result+=i;
    }
    return rsq;
}

void test1()
{
    pthread_t tid;
    Request*rq=new Request(1,100,"Thread 1");
    pthread_create(&tid,nullptr,sumCount,rq);
    void*ret;
    pthread_join(tid,&ret);
    Response*rsp=static_cast<Response*>(ret);
    cout<<"rsp->result:"<<rsp->_result<<",rsp->exitcode:"<<rsp->_exitcode<<endl;
}

string toHex(pthread_t tid)
{
    char hex[64];
    snprintf(hex,sizeof(hex),"%p",tid);
    return hex;
}

void*threadRoutine(void*args)
{
    while(true)
    {
        cout<<"thread id:"<<toHex(pthread_self())<<endl;
        sleep(1);
    }
}

void test2()
{
    pthread_t tid;
    pthread_create(&tid,nullptr,threadRoutine,(void*)"Thread 1");

    pthread_join(tid,nullptr);

}
int main()
{
    //test1();
    test2();
    return 0;
}